/*
 * @Author: lt
 * @Date: 2021-10-25 17:22:04
 * @Last Modified by:   lt
 * @Last Modified time: 2021-10-25 17:22:04
 */
import React, { useEffect, useState, useRef } from 'react';
import { message, Row, Col, Button } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import type { FormInstance } from 'antd/lib/form';
import { history, useModel } from 'umi';
import {
  DribbbleOutlined,
  LockTwoTone,
  QuestionOutlined,
  SafetyOutlined,
  UserOutlined,
} from '@ant-design/icons';
import Footer from '@/components/Footer';
import styles from './index.less';

import { setToken } from '@/utils/utils';

import type { ImageCodeType } from '@/services/login';
import { getImageCode, login } from '@/services/login';

import Setting from './../../../config/defaultSettings';

/**
 * 此方法会跳转到 redirect 参数所在的位置
 */
const goto = () => {
  if (!history) return;
  setTimeout(() => {
    const { query } = history.location;
    const { redirect } = query as { redirect: string };
    history.replace(redirect || '/');
  }, 10);
};

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [imageInfo, setImageInfo] = useState<ImageCodeType>({
    imageCodeKey: '',
    imageCodeBase64: '',
  }); //设置图片验证码

  const loginRef = useRef<FormInstance>(); // 操作修改表单

  //用于设置登录用户
  const fetchUserInfo = async (name: any) => {
    setInitialState({
      ...initialState,
      currentUser: {
        name,
        avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
      },
    });
  };

  /**
   * @description: 请求验证码
   */
  const getImageInfo = async () => {
    let mounted = true;
    if (mounted) {
      //Do Something
      const { data } = await getImageCode();
      setImageInfo(data);
    }
    return function cleanup() {
      mounted = false;
    };
  };

  useEffect(() => {
    getImageInfo();
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        <DribbbleOutlined style={{ fontSize: '24px', marginRight: '24px' }} />
      </div>
      <Button className={styles.help}>
        <QuestionOutlined />
      </Button>
      <div className={styles.content}>
        <div className={styles.header}>
          <span className={styles.logo}>
            <img alt="logo" src="..//logo.svg" />
          </span>
          <span className={styles.title}>{Setting.title}</span>
        </div>
        <div className={styles.desc}>
          Yunnan easy to use software Co., Ltd., Internet information service.
        </div>
        <div className={styles.main}>
          <ProForm
            submitter={{
              searchConfig: {
                submitText: '登录',
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }}
            formRef={loginRef}
            onFinish={async (values) => {
              const params = {
                phone: values.phone,
                password: values.password,
                imageCode: values.imageCode,
                imageCodeKey: imageInfo?.imageCodeKey || '',
              };
              const msg = await login(params);
              if (msg) {
                if (msg?.data) {
                  const { token, name } = msg.data;
                  setToken(token);
                  message.success('登录成功');
                  await fetchUserInfo(name);
                  goto();
                } else {
                  if (msg.code === 50002) {
                    message.error('验证码错误');
                    loginRef.current?.resetFields(['imageCode']);
                    getImageInfo();
                  } else {
                    message.error(msg.message);
                    loginRef.current?.resetFields(['imageCode']);
                    getImageInfo();
                  }
                }
              } else {
                loginRef.current?.resetFields(['imageCode']);
                getImageInfo();
              }
            }}
          >
            <>
              <div className={styles.tabsTop}>
                <div className={styles.countItems}>
                  <span className={styles.tabsTitle}>登录</span>
                </div>
                <div className={styles.boxShadow} />
              </div>
              <div style={{ marginTop: '26px' }}>
                <ProFormText
                  validateTrigger="onBlur"
                  name="phone"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder="请输入手机号"
                  rules={[
                    { required: true, message: '请输手机号!' },
                    { pattern: new RegExp(/^\d{11}$/, 'g'), message: '手机号为11位数字' },
                  ]}
                />
                <ProFormText.Password
                  validateTrigger="onBlur"
                  name="password"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockTwoTone className={styles.prefixIcon} />,
                  }}
                  placeholder="请输入密码"
                  rules={[
                    { required: true, message: '请输入密码！' },
                    {
                      pattern: new RegExp(/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/, 'g'),
                      message: '密码为6-20个字符，由数字 + 字母组成',
                    },
                  ]}
                />
                <Row>
                  <Col span={15}>
                    <ProFormText
                      name="imageCode"
                      placeholder="请输入图片验证码"
                      fieldProps={{
                        size: 'large',
                        prefix: <SafetyOutlined className={styles.prefixIcon} />,
                      }}
                      validateTrigger="onBlur"
                      rules={[
                        { required: true, message: '请输入图片验证码！' },
                        { len: 4, message: '验证码为4个字符' },
                      ]}
                    />
                  </Col>
                  <Col span={9} style={{ textAlign: 'right' }}>
                    <img
                      src={imageInfo?.imageCodeBase64}
                      className={styles.loginImage}
                      onClick={() => {
                        getImageInfo();
                      }}
                    />
                  </Col>
                </Row>
              </div>
            </>
          </ProForm>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
